<?php
/**
 * Created by PhpStorm.
 * User: renshan
 * Date: 16-6-12
 * Time: 上午10:22
 */

namespace Frame\Core\Routing;
use Frame\Core\Kernel\Request;
use Symfony\Component\HttpFoundation\Request as BaseRequest;

/**
 * Class Route
 * @package Frame\Core\Routing
 */
class Route implements RouteInterface
{

    //存储配置文件
    public static $conf;
    //存储路哟规则
    public static $routes = [];
    //存储匹配的路由
    public static $matched;
    //存储访问参数
    public static $params = [];

    /**
     * load routing configuration
     */
    public static function load()
    {
        echo "<pre>";
        if(is_file( _ROOT_.'/App/conf/route.php')) {
            self::$conf = require_once _ROOT_.'/App/conf/route.php';
        }
    }

    /**
     * parse routing configuration
     */
    public static function parse()
    {
        foreach (self::$conf as $r) {
            $r = _ROOT_.'/'.str_replace('\\', '/', $r);
            foreach (require_once ($r) as $k => $v) {
                self::$routes[$k] = $v;
            }
        }
    }

    /**
     * match request and route
     */
    public static function match()
    {
        self::load();
        self::parse();

        $uri = Request::$request->getRequestUri();
        $method = strtolower(Request::$request->getMethod());


        foreach (self::$routes as $k => $r) {

            //构造正则表达式
            $route      = str_replace("/", "\\/", $r['route']);
            $route      = str_replace("?","\?", $route);
            $route      = "/^" . $route . "(\/)?$/";

            //默认请求方法，如果在配置文件中没有指明访问方法，则默认为get
            $methods    = $r['methods'] ? $r['methods'] : ["get"];



            //methods to lowercase
            foreach ($methods as $k => $v) {
                $methods[$k] = strtolower($v);
            }

            preg_match_all('/\{\w+\}/', $route, $m);

            $requirements   = $r['requirements'];


            //匹配requirements没有指定的参数
            foreach ($m as $b) {
                foreach ($b as $c) {
                    $c = ltrim($c,"{");
                    $c = rtrim($c,"}");
                    if (key_exists($c, $requirements)){
                        continue;
                    }
                    $route = str_replace('{'.$c.'}', "\w+", $route);
                }
            }

            $r['route'] = $route;


            //匹配requirements指定的参数
            foreach ($requirements as $k => $v) {
                $k = '{'.$k.'}';
                $route = str_replace($k, $v, $route);
                $m = [];
                if(preg_match_all($route, $uri) && in_array($method, $methods) ) {
                    $r['route'] = $route;
                    self::$matched = $r;
                }
            }
        }

        $route = self::$matched;

        //取值
        /**
         * 1.通过queryString。需要如路已经匹配
         */
        $query_string = Request::$request->getQueryString();
        if($route != null && count($query_string) > 0){
            $queries = explode("&", $query_string);
            foreach ($queries as $q) {
                $arr = explode("=", $q);
                self::$params[$arr[0]] = $arr[1];
            }
        }

        print_r(self::$params);
    }
}